//
//  FQDRadarView.m
//  FakeQDaily
//
//  Created by mewxiv on 9/26/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDRadarView.h"

@implementation FQDRadarPolygonElement

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit
{
    _drawDots = NO;
    _fillColor = [UIColor colorWithWhite:0 alpha:0.8];
}

@end

@interface FQDRadarView ()

@property (nonatomic, strong) NSArray *captionFrames;

@end

@implementation FQDRadarView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    self.backgroundColor = [UIColor whiteColor];
    _minValue = 0;
    _maxValue = 100;
    _radius = MIN(self.frame.size.width / 2 - 18.0f, self.frame.size.height / 2 - 18.0f);
    _centerPoint = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);
    _captionFont = [UIFont systemFontOfSize:10];
    _captionFontColor = [UIColor blackColor];
}

- (void)setPolygonElements:(NSArray<FQDRadarPolygonElement *> *)polygonElements
{
    _polygonElements = polygonElements;
    
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGFloat r = self.radius;
    CGPoint center = self.centerPoint;
    CGFloat minValue = self.minValue;
    CGFloat maxValue = self.maxValue;
    
    // 绘制多边形和顶点
    for (NSInteger elementIndex = 0; elementIndex < [self.polygonElements count]; elementIndex++) {
        FQDRadarPolygonElement *element = self.polygonElements[elementIndex];
        UIColor *strokeColor = element.strokeColor;
        UIColor *fillColor = element.fillColor;
        [strokeColor setStroke];
        [fillColor setFill];
        
        CGFloat radian = (M_PI * 2 / [element.valueList count]);
        for (NSInteger valueIndex = 0; valueIndex < [element.valueList count]; valueIndex++) {
            CGFloat value = [element.valueList[valueIndex] floatValue];
            CGFloat ratio = (value - minValue) / (maxValue - minValue);
            CGFloat valueX = center.x - r * sin(valueIndex * radian) * ratio;
            CGFloat valueY = center.y - r * cos(valueIndex * radian) * ratio;
            if (valueIndex == 0) {
                CGContextMoveToPoint(context, valueX, valueY);
            } else {
                CGContextAddLineToPoint(context, valueX, valueY);
            }
            
        }
        CGFloat firstValue = [[element.valueList firstObject] floatValue];
        CGContextAddLineToPoint(context, center.x, center.y - r * (firstValue - minValue) / (maxValue - minValue));
        strokeColor ? CGContextStrokePath(context) : nil;
        fillColor ? CGContextFillPath(context) : nil;
        
        if (element.drawDots) {
            CGFloat radian = (M_PI * 2 / [element.valueList count]);
            UIColor *outerColor = element.dotOuterColor ? : strokeColor;
            UIColor *innerColor = element.dotInnerColor ? : fillColor;
            if (outerColor || innerColor) {
                for (NSInteger valueIndex = 0; valueIndex < [element.valueList count]; valueIndex++) {
                    CGFloat value = [element.valueList[valueIndex] floatValue];
                    CGFloat ratio = (value - minValue) / (maxValue - minValue);
                    CGFloat valueX = center.x - r * sin(valueIndex * radian) * ratio;
                    CGFloat valueY = center.y - r * cos(valueIndex * radian) * ratio;
                    [outerColor setFill];
                    CGContextFillEllipseInRect(context, CGRectMake(valueX - 4, valueY - 4, 8, 8));
                    [innerColor setFill];
                    CGContextFillEllipseInRect(context, CGRectMake(valueX - 2, valueY - 2, 4, 4));
                }
            }
        }
    }
    
    CGFloat height = [self.captionFont lineHeight];
    CGFloat captionPadding = 4.0;
    
    // 绘制属性文本
    NSMutableArray *mutableFrames = [NSMutableArray arrayWithCapacity:[self.captionList count]];
    FQDRadarPolygonElement *firstElement = [self.polygonElements firstObject];
    CGFloat radian = (M_PI * 2 / [firstElement.valueList count]);
    for (NSInteger captionIndex = 0; captionIndex < [self.captionList count]; captionIndex++) {
        NSString *caption = self.captionList[captionIndex];
        CGPoint vertextPoint = CGPointMake(center.x - r * sin(captionIndex * radian), center.y - r * cos(captionIndex * radian));
        
        CGSize textSize = [caption sizeWithAttributes : @{ NSFontAttributeName : self.captionFont }];
        CGFloat width = textSize.width;
        
        CGFloat xFactor = (vertextPoint.x - center.x);
        xFactor = (xFactor == 0) ? 0 : xFactor / ABS(xFactor);
        CGFloat yFactor = (vertextPoint.y - center.y);
        yFactor = (yFactor == 0) ? 0 : yFactor / ABS(yFactor);
        
        CGFloat xOffset = xFactor * (width / 2.0 + captionPadding);
        CGFloat yOffset = yFactor * (height / 2.0 + captionPadding);
        CGPoint captionCenter = CGPointMake(vertextPoint.x + xOffset, vertextPoint.y + yOffset);
        
        NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
        [paragraphStyle setAlignment:NSTextAlignmentCenter];
        
        NSDictionary *attributes = @{ NSFontAttributeName: self.captionFont,
                                      NSForegroundColorAttributeName : self.captionFontColor,
                                      NSParagraphStyleAttributeName: paragraphStyle};
        
        CGRect captionFrame = CGRectMake(captionCenter.x - width / 2.0, captionCenter.y - height / 2.0, width, height);
        [caption drawInRect:captionFrame withAttributes:attributes];
        [mutableFrames addObject:[NSValue valueWithCGRect:captionFrame]];
    }
    self.captionFrames = mutableFrames;
    
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:self];
    for (NSInteger frameIndex = 0; frameIndex < [self.captionFrames count]; frameIndex++) {
        CGRect attributeFrame = [self.captionFrames[frameIndex] CGRectValue];
        if (CGRectContainsPoint(attributeFrame, touchLocation)) {
            NSString *caption = self.captionFrames[frameIndex];
            if ([self.delegate respondsToSelector:@selector(didTouchedCaption:atIndex:)]) {
                [self.delegate didTouchedCaption:caption atIndex:frameIndex];
            }
        }
    }
}


@end